package com.nulldev.util.web.nCaptcha.backend.user;

import java.util.LinkedList;

import com.nulldev.util.other.ArrayUtils;
import com.nulldev.util.threading.legacy.ThreadExecutor;

public class UserManager {

	private static final LinkedList<User> USERS = new LinkedList<User>();
	
	private static boolean __thread_dispatched;
	static {
		if (!__thread_dispatched) {
			ThreadExecutor.execute(new Runnable() {
				
				@Override
				public void run() {
					while (true) {
						try {
							for (int i = 0; i < USERS.size(); i++) {
								final User user = USERS.get(i);
								// undo bot status
								if (!user.isNotBot()) {
									user.resetCaptchaStatus();
								}
								if (user.isExpired()) {
									USERS.remove(i);
								}
							}
							Thread.sleep(120 * 1000L);
						}catch (Exception e) {
							if (!(e instanceof InterruptedException)) {
								e.printStackTrace();
							}
						}
					}
				}
			});
			__thread_dispatched = true;
		}
	}
	
	public static User registerOrLoadUser(final String ip) {
		User output = null;
		for (final User user : (LinkedList<User>) USERS.clone()) {
			if (user.getIP().equals(ip)) {
				return user;
			}
		}
		output = new User(ip);
		USERS.add(output);
		return output;
	}

	public static boolean removeUser(final User user) {
		return USERS.remove(user);
	}
}
